import json

from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
import re
from django.contrib.auth import authenticate, login

from django import http
from users.models import User,Address
from meiduo_mall.utils import constants
from meiduo_mall.utils.my_encrypt import generate_verify_url, decode_verify_url
from meiduo_mall.utils.my_loginview import LoginRequiredView

# Create your views here.


# 用户注册视图
from meiduo_mall.utils.response_code import RET
from celery_tasks.mail.tasks import send_verify_email

class Register(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        name = request.POST.get('user_name')
        password = request.POST.get('pwd')
        cpassword = request.POST.get('cpwd')
        mobile = request.POST.get('phone')
        msg_code = request.POST.get('msg_code')
        allow = request.POST.get('allow')
        print(allow)
        # 校验为空
        if not all([name, password, cpassword, mobile, msg_code, allow]):
            return HttpResponse('参数不全')
        if password != cpassword:
            return HttpResponse("两次密码不一致")
        if not re.match('^1[3-9]\d{9}', mobile):
            return HttpResponse('手机号格式不正确')
        print('msg_code != %s' % (msg_code))

        if allow != 'on':
            return HttpResponse('协议需要同意')
        user = User.objects.create_user(username=name, password=password, mobile=mobile)

        return redirect('http://www.taobao.com')


# 判断用户是否存在
class UsernameCountview(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        # if count > 0:
        #     return HttpResponse('用户名已存在')
        # else:
        #     return HttpResponse('用户名正确')
        return http.JsonResponse({'count': count, 'code':RET.OK})


# 判断手机号是否存在
class Usermobileview(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'count': count, 'code': RET.OK})


# 用户登录视图
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        remembered = request.POST.get('remembered')

        # 判断为空
        if not all(['username', 'password']):
            return http.HttpResponseForbidden('参数不全')

        # 判断用户名格式是否正确
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('用户名合适不正确')
        # 判断密码格式是否正确
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden('密码格式不正确')

        # 判断账号和密码是否正确
        user = authenticate(request, username=username, password=pwd)

        if not user:
            return http.HttpResponseForbidden('账号或者密码不正确')

        # 状态保持
        login(request, user)  # 就是讲用户的信息储存在session
        if remembered == 'on':
            request.session.set_expiry(constants.REDIS_SESSION_COOKIE_REPIRES)  # 信息保存两天

        else:
            request.session.set_expiry(0)  # 浏览器会话结束

        response = redirect('/')
        response.set_cookie('username', user.username, constants.REDIS_SESSION_COOKIE_REPIRES)
        return response


# 5, 用户中心

class UserInfoView(LoginRequiredView):


    def get(self, request):
        # 1, 第一种: 传统方式, 判断用户是否登录
        # if request.user.is_authenticated:
        #     return render(request,'user_center_info.html')
        # else:
        #     return redirect("/login")

#       #1，拼接数据，当用户登陆之后，
        context = {
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':False,
            "email_active": request.user.email_active
        }

        #2,渲染页面

        return render(request, 'user_center_info.html',context=context)


#6发送邮件
class EmailView(LoginRequiredView):
    def put(self,request):
        #1,获取参数
        email = json.loads(request.body.decode()).get('email')
        #校验参数
        if not email:
            return http.JsonResponse({'code':RET.PARAMERR,'errmsg':'参数不全'})
        #3，数据入库，发送邮件
        verify_url = generate_verify_url(request.user,email)
        #使用selery发送邮件
        send_verify_email.delay(verify_url,email)


        # result = send_mail(subject ='美多商城，验证链接',message='激活链接...',recipient_list=[email],from_email=settings.EMAIL_FROM)
        # #3.1判断发送是否成功
        # if result !=1:
        #     return http.JsonResponse({'code':RET.THIRDERR,'errmsg':'邮件发送失败'})
        #3,2 数据入库
        request.user.email = email
        request.user.save()
        #返回响应
        return http.JsonResponse({'code':RET.OK,'errmsg':'发送成功'})


#7, 验证邮件
class VerifyEmailView(View):
    def get(self,request):
        #1,获取token参数
        token = request.GET.get('token')

        #2,解密token
        user = decode_verify_url(token)

        if not user:
            return http.HttpResponseForbidden("token失效")

        #3,修改邮件的激活状态
        user.email_active = True
        user.save()

        #4,返回响应
        return redirect("/info")


#8, 收货地址
class AddressesView(View):
    def get(self,request):
        # 1,查询用户的地址
        # addresses = Address.objects.filter(user_id=request.user.id).all()
        addresses = request.user.addresses.filter(is_delete=False).all()

        # 2,拼接数据
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
            addresses_list.append(address_dict)

        context = {
            "addresses": addresses_list,
        }

        return render(request,'user_center_site.html',context=context)


#9, 新增地址
class AddressesCreateView(View):
    def post(self,request):
        #1,获取参数
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        #2,校验参数
        if not all([title,receiver,province_id,city_id,district_id,place,mobile,tel,email]):
                return http.JsonResponse({"code":RET.PARAMERR,"errmsg":"参数不全"})

        #3,数据入库
        data_dict["user_id"] = request.user.id
        address = Address.objects.create(**data_dict)

        #4,返回响应
        data_dict = {
            "code":RET.OK,
            "address":{
                "id":address.id,
                "title":address.title,
                "receiver":address.receiver,
                "province":address.province.name,
                "city":address.city.name,
                "district":address.district.name,
                "place":address.place,
                "mobile":address.mobile,
                "tel":address.tel,
                "email":address.email,
                "province_id":address.province_id,
                "city_id":address.city_id,
                "district_id":address.district_id,
            }
        }
        return http.JsonResponse(data_dict)


#10, 修改地址,删除地址
class AddressesUpdateView(View):
    def put(self,request,address_id):
        #1,获取参数
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        #2,校验参数
        if not all([title,receiver,province_id,city_id,district_id,place,mobile,tel,email]):
                return http.JsonResponse({"code":RET.PARAMERR,"errmsg":"参数不全"})

        #3,数据入库,返回的数据是整数,表示修改的行数
        try:
            del data_dict["id"]
            del data_dict["province"]
            del data_dict["city"]
            del data_dict["district"]
            ret = Address.objects.filter(id=address_id).update(**data_dict)
            address = Address.objects.get(id=address_id)
        except Exception as e:
            return http.JsonResponse({"code": RET.DATAERR, "errmsg": "修改失败"})

        #4,返回响应
        data_dict = {
            "code":RET.OK,
            "address":{
                "id":address.id,
                "title":address.title,
                "receiver":address.receiver,
                "province":address.province.name,
                "city":address.city.name,
                "district":address.district.name,
                "place":address.place,
                "mobile":address.mobile,
                "tel":address.tel,
                "email":address.email,
                "province_id":address.province_id,
                "city_id":address.city_id,
                "district_id":address.district_id,
            }
        }
        return http.JsonResponse(data_dict)

    def delete(self, request, address_id):
        # 1,数据入库
        try:
            ret = Address.objects.filter(id=address_id).update(is_deleted=True)
        except Exception as e:
            return http.JsonResponse({"code": RET.DBERR, "errmsg": "删除失败"})

        # 2,返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "删除成功"})

#11, 设置默认
class AddressesDefaultView(LoginRequiredView):
    def put(self,request,address_id):

        #1,数据入库
        try:
            request.user.default_address_id = address_id
            request.user.save()
        except Exception as e:
            return http.JsonResponse({"code":RET.DBERR,"errmsg":"设置默认失败"})

        #2,返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "修改城改"})

#12, 标题修改
class AddressesTitleView(View):
    def put(self,request,address_id):
        #1,获取参数
        title = json.loads(request.body.decode()).get("title")

        #2,校验参数
        if not title:
            return http.JsonResponse({"code":RET.PARAMERR,"errmsg":"参数不全"})

        #3,数据入库
        try:
            Address.objects.filter(id=address_id).update(title=title)
        except Exception as e:
            return http.JsonResponse({"code": RET.DBERR, "errmsg": "修改失败"})

        #4,返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "修改成功"})

